package com.xmg.p2p.base.controller;

import com.xmg.p2p.base.domain.Logininfo;
import com.xmg.p2p.base.service.IAccountService;
import com.xmg.p2p.base.service.IUserinfoService;
import com.xmg.p2p.base.util.BidConst;
import com.xmg.p2p.base.util.UserContext;
import com.xmg.p2p.business.domain.BidRequest;
import com.xmg.p2p.business.service.IBidRequestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class BorrowController {
    @Autowired
    private IAccountService accountService;
    @Autowired
    private IUserinfoService userinfoService;
    @Autowired
    private IBidRequestService bidRequestService;

    @RequestMapping("borrow")
    public String borrowIndex(Model model) {
        Logininfo current = UserContext.getCurrent();
        if (current == null) {
            return "redirect:borrow.html";
        }
        model.addAttribute("account", accountService.get(current.getId()));
        model.addAttribute("userinfo", userinfoService.getCurrent());
        model.addAttribute("creditBorrowScore", BidConst.BASE_BORROW_SCORE);
        return "borrow";
    }

    @RequestMapping("borrowInfo")
    public String borrowInfo(Model model) {
        Long id = UserContext.getCurrent().getId();
        if (bidRequestService.canApplyBidRequest(id)) {
            model.addAttribute("minBidRequestAmount",
                    BidConst.SMALLEST_BIDREQUEST_AMOUNT);// 最小借款金额
            model.addAttribute("minBidAmount", BidConst.SMALLEST_BID_AMOUNT);// 系统规定的最小投标金额
            model.addAttribute("account", this.accountService.get(id));
            return "borrow_apply";
        } else {
            return "borrow_apply_result";
        }
    }

    @RequestMapping("borrow_apply")
    public String borrowApply(BidRequest bidRequest) {
        bidRequestService.apply(bidRequest);
        return "redirect:/borrowInfo.do";
    }
}
